import request from '@/utils/request';
import type {
  Chapter,
  IProduct,
  IAddProduct,
  ISearchParams,
  IChapter,
} from '@/types/request';
import type { TransformValueOfProduct } from '@/types/table-transform';
import {} from '../types/request';

// 获取课程列表
export function searchProduct(options: Omit<ISearchParams, 'total'>) {
  let params: Omit<ISearchParams, 'total'> = {
    page: options.page,
    size: options.size,
  };
  return request<IProduct, true>(
    `/product${options?.condition ? '/' + options.condition : ''}`,
    { params }
  );
}

export function getChaptersAndEpisodes(id: number) {
  return request<IChapter[]>(`/product/chaptersAndEpisodes/${id}`);
}

// 删除课程
export function deleteProduct(id: string) {
  return request(`/product/${id}`, { method: 'DELETE' });
}

// 修改课程
export function updateProduct(data: TransformValueOfProduct) {
  return request(`/product/${data.id}`, {
    method: 'PUT',
    data: { updated_details: data },
  });
}

// 创建课程
export function addProduct(options: {
  cover_img: File;
  new_details: IAddProduct;
  chapters: Chapter[];
}) {
  // create a form data
  const formData = new FormData();
  formData.append('cover_img', options.cover_img);
  formData.append('new_details', JSON.stringify(options.new_details));
  formData.append('chapters', JSON.stringify(options.chapters));
  return request('/product', {
    method: 'POST',
    data: formData,
    headers: { 'Content-Type': 'multipart/form-data' },
  });
}
